package com.yupi.yupicturebackend.api.baidu.imageUnderstand.sub;

import cn.hutool.json.JSONObject;
import okhttp3.*;
import java.io.IOException;

public class ImageUnderstandingTaskQuery {
    private  String accessToken;
    private final OkHttpClient httpClient;

    public ImageUnderstandingTaskQuery(String accessToken, OkHttpClient httpClient) {
        this.accessToken = accessToken;
        this.httpClient = httpClient;
    }

    public void updateAccessToken(String newAccessToken) {
        this.accessToken = newAccessToken;
    }

    public JSONObject getTaskResult(String taskId) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject requestBody = new JSONObject();
        requestBody.put("task_id", taskId);

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-classify/v1/image-understanding/get-result?access_token=" + accessToken)
                .post(RequestBody.create(requestBody.toString(), mediaType))
                .addHeader("Content-Type", "application/json")
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            // 检查 response.body() 是否为 null，避免 NullPointerException
            ResponseBody responseBodyObj = response.body();
            if (responseBodyObj == null) {
                throw new IOException("Response body is null");
            }
            return new JSONObject(responseBodyObj.string());
        }
    }
}